#include "include.h"

/*

    函数功能：nvs初始化
    函数名称：lonon_nvs_flash_init

*/
void lonon_nvs_flash_init()
{
    // Initialize NVS
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        // NVS partition was truncated and needs to be erased
        // Retry nvs_flash_init
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK( err );    
}
/*

    函数功能：数据读取
    函数名称：lonon_nvs_get_str
    输入：*name             文件名
    输入：key               键
    输出：*out_value        值
    输出：*length           输出值长度
    返回：成功     ESP_OK   其他失败

*/
esp_err_t lonon_nvs_get_str(char* name,char* key, char* out_value, size_t* length)
{
    esp_err_t ret = ESP_FAIL;
    esp_err_t err;
    nvs_handle_t my_handle;
    err = nvs_open(name, NVS_READWRITE, &my_handle);
    if (err != ESP_OK) {
        printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
    } 
    else 
    {
        ret = nvs_get_str(my_handle, key, out_value,length);
    }

    nvs_close(my_handle);

    return ret;
}
/*

    函数功能：数据存储
    函数名称：lonon_nvs_set_str
    输入：*name             文件名
    输入：key               键
    输出：*value            值
    输出：*length           输出值长度
    返回：成功     ESP_OK   其他失败

*/
esp_err_t lonon_nvs_set_str(char* name,char* key, char* value)
{
    esp_err_t ret = ESP_FAIL;
    esp_err_t err;
    nvs_handle_t my_handle;
    err = nvs_open(name, NVS_READWRITE, &my_handle);
    if (err != ESP_OK) {
        printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
    } 
    else 
    {
        ret = nvs_set_str(my_handle, key, value);
    }

    nvs_commit(my_handle);
    nvs_close(my_handle);
    
    return ret;
}
